package com.example.ncov_management_system.service;

import com.example.ncov_management_system.dao.TeacherDao;
import com.example.ncov_management_system.entity.Clbum;
import com.example.ncov_management_system.entity.Login;
import com.example.ncov_management_system.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private LoginService loginService;
    @Autowired
    private ClbumService clbumService;

    public List<Teacher> list() {
        return teacherDao.findAll();
    }
    @Transactional
    public void add(Teacher teacher,long[] ids) {
        if (ids != null) {
            List<Clbum> clbums = clbumService.findByIds(ids);
            for (Clbum clbum : clbums) {
                clbum.setTeacher(teacher);
            }
            teacher.setClbums(clbums);
        }
        Teacher save = teacherDao.save(teacher);
        Login login = new Login();
        login.setRole("教师");
        login.setPassword("123456");
        login.setUsername(save.getId() + "");
        loginService.add(login);
    }


    @Transactional
    public Teacher findById(long id) {
        return teacherDao.findById(id).orElse(null);
    }

    public void edit(Teacher teacher, long[] ids) {
        List<Clbum> clbumslist = teacherDao.findById(teacher.getId()).get().getClbums();
        for (Clbum clbum : clbumslist) {
            clbum.setTeacher(null);
        }
        if (ids != null) {
            List<Clbum> clbums = clbumService.findByIds(ids);
            for (Clbum clbum : clbums) {
                clbum.setTeacher(teacher);
            }
            teacher.setClbums(clbums);
        }
        teacherDao.save(teacher);
    }

    @Transactional
    public void delete(long id) {
        Teacher teacher = this.findById(id);
        for (Clbum clbum : teacher.getClbums()) {
            clbum.setTeacher(null);
        }
        loginService.deleteByUsername(id+"");
        teacherDao.deleteById(id);
    }
}
